#include <stdio.h>
#include <stdlib.h>
#include "../common.h"
#include "./memory.h"
#include "./list.h"

list_node_t* list_construction()
{
	return NULL;
}


list_node_t* list_add(list_node_t* list_p,int k, int v)
{
	if(list_p == NULL)
	{
		list_p = (list_node_t*)my_malloc(sizeof(list_node_t));
		ASSERT(list_p);
		list_p -> next  = list_p;
		list_p -> prev  = list_p;
		list_p -> key   = k;
		list_p -> value = v;
		return list_p;
	} else
	{
		list_node_t *temp = (list_node_t*)my_malloc(sizeof(list_node_t));
		ASSERT(temp);
		temp -> key = k;
		temp -> value = v;
		temp -> next = list_p -> next;
		temp -> prev = list_p -> next -> prev; //~? temp = list_p
		list_p -> next -> prev = temp;
		list_p -> next = temp;
    return temp;
	}
}
		

list_node_t* list_node_del(list_node_t* list_d)
{
	if (list_d == NULL)
	{
		printf("List is empty\n");
		exit(1);					
	}
	if (list_d ->  next == list_d)
	{
		my_free(list_d);
		list_d = NULL;
	} else
	{
		list_node_t *after_node = list_d -> next;
		list_d -> prev -> next = list_d -> next;
		list_d -> next -> prev = list_d -> prev;
		my_free(list_d);
		list_d = after_node;
	}
	return list_d;
}

void list_destruct(list_node_t* list_d)
{
	while(list_d != NULL)
	{
		list_d = list_node_del(list_d);
	}
}

list_node_t* list_find(list_node_t* node_f, int k)
{
	if(node_f != NULL)
	{
		list_node_t *current = node_f;
   	 	do 
    	{
    	    if ( current -> key == k )
        	    return (list_node_t*)current;
        	current = current -> next;
    	} while ( current != node_f );
    } else { return NULL; }
    return NULL;
}

list_node_t* list_next(list_node_t* list_n)
{
	ASSERT(list_n);
	list_n = list_n -> next;
	return list_n;
}

list_node_t* list_prev(list_node_t* list_pre)
{
	ASSERT(list_pre);
	list_pre = list_pre -> prev;
	return list_pre;
}
